package com.ktjy.ktmall.servlet;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.ktjy.ktmall.entity.AjaxResult;
import com.ktjy.ktmall.entity.Menu;
import com.ktjy.ktmall.service.MenuService;
import com.ktjy.ktmall.service.impl.MenuServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet(name = "MenuServlet", urlPatterns = "/uni/xtgl/menu")
public class MenuServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        String params = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        System.out.println(params);
        // 3、将请求参数字符串转换成JSONObject对象，之后从JSONObject对象中取出值
        JSONObject entries = JSONUtil.parseObj(params);
        String opr = entries.get("opr", String.class);
        String currPageNo = entries.get("currPageNo", String.class);
        String pageSize = entries.get("pageSize", String.class);
        MenuService menuService = new MenuServiceImp();
        AjaxResult result = null;
        switch (opr) {
            case "page":
                List<Menu> menuList = menuService.getMenuList(Integer.parseInt(currPageNo), Integer.parseInt(pageSize));
                result = AjaxResult.success("用户列表加载成功!", menuList);
                break;
            case "insert":
                break;
        }
        // 将result对象转换成JSON字符串再响应到小程序端
        out.print(JSONArray.toJSONString(result));
        out.flush();
        out.close();
    }
}

